package org.jeecg.modules.foc.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.TypeUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import dm.jdbc.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.c.entity.MSignal;
import org.jeecg.modules.c.service.IMSignalService;
import org.jeecg.modules.c.service.IMSiteService;
import org.jeecg.modules.concat.FocConcat;
import org.jeecg.modules.foc.entity.FocDevice;
import org.jeecg.modules.foc.entity.FocPoint;
import org.jeecg.modules.foc.entity.FocSpace;
import org.jeecg.modules.foc.mapper.FocPointMapper;
import org.jeecg.modules.foc.service.IFocDeviceService;
import org.jeecg.modules.foc.service.IFocPointService;
import org.jeecg.modules.foc.service.IFocSpaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 点位管理
 * @Author: jeecg-boot
 * @Date: 2025-01-10
 * @Version: V1.0
 */
@Service
@Slf4j
public class FocPointServiceImpl extends ServiceImpl<FocPointMapper, FocPoint> implements IFocPointService {
    @Autowired
    private IFocDeviceService focDeviceService;
    @Autowired
    private IFocSpaceService focSpaceService;
    @Autowired
    private IMSignalService mSignalService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void toPointConver(FocPoint focPoint) {
        log.info("点位转换：" + JSONObject.toJSONString(focPoint));
        MSignal mSignal = new MSignal();
        mSignal.setScid(FocConcat.SCID);
        //自动成监控标识id
        // "250034320000000000085971"
        FocDevice focDevice = focDeviceService.getOne(new QueryWrapper<FocDevice>().eq("guid", focPoint.getParentGuid()));
        //获取设备信息
        String deviceidAll = focDevice.getDeviceid();
        if (StringUtil.isEmpty(deviceidAll)) {
            throw new RuntimeException("设备信息编码未设置");
        }
        String deviceId = focDevice.getDeviceNewId();
        mSignal.setSignalname(focPoint.getMpPointName());
        String sellno = "1";
        //根据名称中的阿拉伯数字
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(focPoint.getName());
        if (matcher.find()) {
            sellno = matcher.group(0);
        }
        // 将数字转换为16进制字符串，并补零到指定长度
        String sellnoHex = "001";
        if (focPoint.getSecno() != null) {
            sellnoHex = toPaddedHexString(focPoint.getSecno(), 3);
        } else {
            sellnoHex = toPaddedHexString(TypeUtils.castToInt(sellno), 3);
        }
        log.info("点位序号：" + sellnoHex + "找到的数字:" + sellno);
        String singID = FocConcat.SCID + FocConcat.SUID + deviceId + focPoint.getMpCode() + sellnoHex;
        //    String singID = deviceidAll + focPoint.getMpCode() + sellnoHex;
        mSignal.setId(singID);
        focPoint.setCnId(focPoint.getCnId());
        this.updateById(focPoint);
        mSignal.setDeviceid(deviceId);
        // wd 点位分类Point type：1=AI；2=DI；3=AO；//4=DO；5=Alarm。
        //c  Analog = ListUtil.of(3,5);  Digital =  ListUtil.of(2,4);
        switch (focPoint.getPointType()) {
            case "1":
                mSignal.setType("3");
                break;
            case "2":
                mSignal.setType("2");
                break;
            case "3":
                mSignal.setType("5");
                break;
            case "4":
                mSignal.setType("4");
                break;
            case "5":
                mSignal.setType("2");
                mSignal.setArarml(5);
                break;
        }
        mSignal.setGuid(focPoint.getGuid());
        //机房
        FocSpace roomSpec = focSpaceService.getOne(new QueryWrapper<FocSpace>().eq("guid", focDevice.getParentGuid()));
        if (roomSpec == null) {
            throw new RuntimeException("未查询到机房：" + focDevice.getParentGuid());
        }
        //局站
        FocSpace sideSPec = focSpaceService.getOne(new QueryWrapper<FocSpace>().eq("guid", roomSpec.getParentGuid()));
        if (sideSPec == null) {
            throw new RuntimeException("未查询到局站：" + roomSpec.getParentGuid());
        }
        mSignal.setSiteid(sideSPec.getSiteid());
        //这个信号
        QueryWrapper<MSignal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("guid", focPoint.getGuid());
        MSignal one = mSignalService.getOne(queryWrapper);
        if (one != null) {
            log.info("更新信号：" + JSONObject.toJSONString(mSignal));
            mSignalService.remove(queryWrapper);
        }
        log.info("保存信号：" + JSONObject.toJSONString(mSignal));
        //判断id是否存在，如果存在，则抛出信号名称
        try {
            mSignalService.save(mSignal);
        } catch (Exception e) {
            log.error("保存错误信号：" + JSONObject.toJSONString(mSignal), e);
            QueryWrapper oldSinQw = new QueryWrapper<>();
            oldSinQw.eq("id", mSignal.getId());
            MSignal one1 = mSignalService.getOne(oldSinQw);
            //查询对应的原始数据
            QueryWrapper oldSinQw1 = new QueryWrapper<>();
            oldSinQw1.eq("guid", one1.getGuid());
            FocPoint one2 = this.getOne(oldSinQw1);
            throw new RuntimeException("配置重复：" + JSONObject.toJSONString(one2));
        }

    }

    /**
     *取消信号映射
     * @param byId
     */
    @Override
    public void cancleMapping(FocPoint byId) {
        //1更新字段为null.
        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("cn_id", null);
        updateWrapper.set("mp_code", null);
        updateWrapper.set("mp_point_name", null);
        updateWrapper.set("secno", null);
        updateWrapper.set("mp_porint_type", null);
        updateWrapper.set("mp_device_type", null);
        updateWrapper.set("mp_big_type", null);
        updateWrapper.set("mp_alarm", null);
        updateWrapper.eq("id", byId.getId());
        this.update(updateWrapper);

        //2删除信号表数据
        QueryWrapper<MSignal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("guid", byId.getGuid());
        mSignalService.remove(queryWrapper);

    }


    /**
     * 将数字转换为16进制字符串，并补零到指定长度
     *
     * @param number       要转换的数字
     * @param targetLength 目标字符串的最小长度（不足时补零）
     * @return 补零后的16进制字符串
     */
    public static String toPaddedHexString(int number, int targetLength) {
        // 使用String.format格式化，%0X表示以16进制输出，0表示补零，targetLength表示总长度
        return String.format("%0" + targetLength + "X", number);
    }

    public static void main(String[] args) {
        String sellno = "1";
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher("15#电池电压事件_过高");
        if (matcher.find()) {
            sellno = matcher.group(0);
        }
        String sellnoHex = toPaddedHexString(TypeUtils.castToInt(sellno), 3);
        log.info("点位序号：" + sellnoHex, "找到的数字:" + sellno);

    }

}
